// ReSharper disable SuggestUseVarKeywordEvident
using System.IO;
using System.Reflection;
using System.Xml.Serialization;

namespace bnab.DataModel
{
  public static class Settings
  {
    private static SettingsData _data;

    static Settings()
    {
      Load();
    }

    #region Properties

    public static int BalanceWarning
    {
      get { return _data.BalanceWarning == 0 ? 110000 : _data.BalanceWarning; }
      set { _data.BalanceWarning = value; }
    }

    public static string Login
    {
      get { return _data.Login; }
      set { _data.Login = value; }
    }

    public static string Password
    {
      get { return _data.Password; }
      set { _data.Password = value; }
    }

    public static ProxyChoice ProxyChoice
    {
      get { return _data.ProxyChoice; }
      set { _data.ProxyChoice = value; }
    }

    public static string ProxyUrl
    {
      get { return _data.ProxyUrl; }
      set { _data.ProxyUrl = value; }
    }

    public static ushort ProxyPort
    {
      get
      {
        return _data.ProxyPort == 0 ? (ushort)8080 : _data.ProxyPort;
      }
      set { _data.ProxyPort = value; }
    }

    public static string ProxyLogin
    {
      get { return _data.ProxyLogin; }
      set { _data.ProxyLogin = value; }
    }

    public static string ProxyPassword
    {
      get { return _data.ProxyPassword; }
      set { _data.ProxyPassword = value; }
    }

    public static bool Valid
    {
      get
      {
        return
          !string.IsNullOrEmpty(_data.Login) &&
          !string.IsNullOrEmpty(_data.Password);
      }
    }
    #endregion


    public static void Save()
    {
      if (_data == null)
      {
        _data = new SettingsData();
      }
      using (Stream stream = new FileStream(GetSettingsFileName(), FileMode.Create, FileAccess.Write, FileShare.None))
      {
        XmlSerializer xs = new XmlSerializer(typeof(SettingsData));
        xs.Serialize(stream, _data);
      }
    }

    private static void Load()
    {
      if (_data != null)
      {
        return;
      }
      string fileName = GetSettingsFileName();
      if (!File.Exists(fileName))
      {
        _data = new SettingsData();
      }

      XmlSerializer xs = new XmlSerializer(typeof(SettingsData));
      try
      {
        using (Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
          _data = (SettingsData)xs.Deserialize(stream);
        }
      }
      catch
      {
        _data = new SettingsData();
      }
    }

    private static string GetSettingsFileName()
    {
      return Path.ChangeExtension(Assembly.GetExecutingAssembly().Location, "xml");
    }
  }
}
// ReSharper restore SuggestUseVarKeywordEvident
